﻿using Lazy.Captcha.Core;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace Devonline.AspNetCore;

/// <summary>
/// 验证码服务
/// </summary>
public class CaptchaService(ILogger<CaptchaService> logger, ICaptcha captcha, HttpSetting httpSetting) : ICaptchaService
{
    private readonly ILogger<CaptchaService> _logger = logger;
    private readonly ICaptcha _captcha = captcha;
    private readonly HttpSetting _httpSetting = httpSetting;
    private readonly string _userAccess = $"In access index {KeyGenerator.GetStringKey()}";

    /// <summary>
    /// 获取验证码
    /// </summary>
    /// <param name="captchaId">验证码编号</param>
    /// <returns></returns>
    /// <exception cref="BadHttpRequestException"></exception>
    public IActionResult GetCaptcha(string captchaId)
    {
        _logger.LogDebug($"{_userAccess}: will get the CAPTCHA for: {captchaId}");
        var captchaData = _captcha.Generate(captchaId, _httpSetting.CaptchaExpireTime);
        if (captchaData is null)
        {
            throw new BadHttpRequestException("验证码获取失败, 请刷新后再次尝试!");
        }

        _logger.LogInformation($"{_userAccess}: get the CAPTCHA for: {captchaId} success!");
        return new FileContentResult(captchaData.Bytes, ContentType.Png) { FileDownloadName = "captcha.png" };
    }
    /// <summary>
    /// 获取验证码
    /// </summary>
    /// <param name="captchaId">验证码编号</param>
    /// <returns></returns>
    /// <exception cref="NotImplementedException"></exception>
    public async Task<IActionResult> GetCaptchaAsync(string captchaId) => await Task.FromResult(GetCaptcha(captchaId));

    /// <summary>
    /// 验证当前验证码
    /// </summary>
    /// <param name="captchaId">验证码编号</param>
    /// <param name="captcha">当前验证码</param>
    /// <returns></returns>
    /// <exception cref="NotImplementedException"></exception>
    public bool Validate(string captchaId, string captcha)
    {
        _logger.LogDebug($"{_userAccess}: will validate the CAPTCHA for: {captchaId} with captcha value: {captcha}");
        var result = _captcha.Validate(captchaId, captcha);
        if (result)
        {
            _logger.LogInformation($"{_userAccess}: validate the CAPTCHA for: {captchaId} success!");
        }
        else
        {
            _logger.LogInformation($"{_userAccess}: validate the CAPTCHA for: {captchaId} failed, please try again later!");
        }

        return result;
    }
    /// <summary>
    /// 验证当前验证码
    /// </summary>
    /// <param name="captchaId">验证码编号</param>
    /// <param name="captcha">当前验证码</param>
    /// <returns></returns>
    /// <exception cref="NotImplementedException"></exception>
    public async Task<bool> ValidateAsync(string captchaId, string captcha) => await Task.FromResult(Validate(captchaId, captcha));
}